package com.binvshe.binvshe.mine.usercenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.app.home.adapter.HomeAdapter;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.huanxin_im.ChatHelper;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.entity.HomeEntity;
import com.binvshe.binvshe.mine.view.CommentDialog;
import com.binvshe.binvshe.organization.OpusAdapter;
import com.binvshe.binvshe.organization.entity.OpusListEntity;
import com.bumptech.glide.Glide;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.nineoldandroids.view.ViewHelper;
import com.pachong.android.baseuicomponent.activity.SwipeListActivity;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.ColorFilterTransformation;
import jp.wasabeef.glide.transformations.gpu.VignetteFilterTransformation;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/9/19
 */
public class UserCenterActivity extends SwipeListActivity implements ObservableScrollViewCallbacks, View.OnClickListener {
    private static final String KEY_USERID = "USER_ID";
    private static final int SHOW_MINE = 881;
    private static final int SHOW_OTHER = 777;
    private static final int SHOW_VIESITOR = 956;
    View mHeaderView;


    int mFollowState = -1;

    @InjectExtra(KEY_USERID)
    String mUserid;

    boolean isHide = false;
    ListDataRequestListener<HomeEntity> mRequestListener = new ListDataRequestListener(this, HomeEntity.class);
    int mPage;
    @Bind(R.id.obsRecyclerview)
    ObservableRecyclerView mObsRecyclerview;
    @Bind(R.id.btnFloating)
    Button mBtnFloating;
    @Bind(R.id.swlyt_swip)
    SwipeRefreshLayout mSwlytSwip;
    @Bind(R.id.btnSendMessage)
    Button mBtnSendMessage;
    private CircleImageView civHead;
    private TextView tvClubName;
    private TextView tvClubPlace;
    private TextView tvFansNum;
    private TextView tvClubID;
    private Button btnAttention;
    private TextView tvUserSign;
    private RelativeLayout relytViewHeader;
    private ImageView mViewHeader;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("jinlaiActivite", "dfdsfdsfdsfsdf");

        Dart.inject(this);


        super.onCreate(savedInstanceState);
        mHeaderView = getLayoutInflater().inflate(R.layout.view_usercenter_header, null, false);
        this.relytViewHeader = (RelativeLayout) mHeaderView.findViewById(R.id.relytViewHeader);
        this.mViewHeader = (ImageView) mHeaderView.findViewById(R.id.viewHeader);
        this.tvUserSign = (TextView) mHeaderView.findViewById(R.id.tvUserSign);
        this.btnAttention = (Button) mHeaderView.findViewById(R.id.btnAttention);
        this.tvClubID = (TextView) mHeaderView.findViewById(R.id.tvClubID);
        this.tvFansNum = (TextView) mHeaderView.findViewById(R.id.tvFansNum);
        this.tvClubPlace = (TextView) mHeaderView.findViewById(R.id.tvClubPlace);
        this.tvClubName = (TextView) mHeaderView.findViewById(R.id.tvClubName);
        this.civHead = (CircleImageView) mHeaderView.findViewById(R.id.civHead);
        btnAttention.setOnClickListener(this);
        mBtnSendMessage.setVisibility(View.GONE);
        getAdapter().setHeaderView(mHeaderView);
        initTitle();
        initShowType();
        getUserInfo();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initTitle() {
        enableBackButton();
//        getCustomToolbar().setBackgroundColor(getResources().getColor(R.color.lightBlue));
//        getCustomToolbar().enableBackButton(getResources().getDrawable(R.mipmap.share_nav_button_back_default_w));
    }

    @Override
    protected void onResume() {
        super.onResume();
        onStartLoading();
    }

    @Override
    public View createRecyclerContentView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.observable_recyclerview, null);
        ButterKnife.bind(this, view);
        setRecyclerView(mObsRecyclerview);
        mSwipeRefreshViewHelper.initRefreshView(mSwlytSwip, this);
        mObsRecyclerview.setScrollViewCallbacks(this);
        return view;
    }

    protected void setShowType(int showType) {
        mShowType = showType;
        switch (showType) {
            case SHOW_MINE:
                btnAttention.setVisibility(View.INVISIBLE);
                btnAttention.setClickable(false);
                mBtnFloating.setVisibility(View.GONE);
//                ((OpusAdapter)getAdapter()).setJBulderType(OpusAdapter.JBulderType.DELETE);
                break;
            case SHOW_OTHER:
                btnAttention.setVisibility(View.VISIBLE);
                mBtnFloating.setVisibility(View.VISIBLE);

                break;
            case SHOW_VIESITOR:
                break;
        }
    }

    int mShowType;//显示自己的还是他人的

    public static void start(Context context, String userid) {
        Intent starter = new Intent(context, UserCenterActivity.class);
        starter.putExtra(KEY_USERID, userid);
        context.startActivity(starter);
    }

    /**
     * 判断是否为自己的空间
     */
    private void initShowType() {
        if (AccountManager.isTokenValid()) {
            if (TextUtils.equals(mUserid + "", AccountManager.getCurrentAccount().getUserId())) {
                setShowType(SHOW_MINE);
                return;
            }
        }
        setShowType(SHOW_OTHER);
        Log.e("setShowType", "不是自己的");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnAttention:
                switch (mFollowState) {
                    case 2:
                    case 3:
                        deleteAttention();
                        break;
                    case 0:
                    case 1:
                        addAttention();
                        break;
                }
                break;
        }
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new HomeAdapter(this);
    }

    @Override
    public void onStartLoading() {
        getOpusList();
    }

    /**
     * 获取列表数据
     */
    public void getOpusList() {
        if (mPage == 0 || mRequestListener.getResponseDataParser().hasMore()) {
            mPage++;
            IHttpRequest request = new MyHttpRequest(this);
            UrlParams params = new UrlParams();
            params.put("page", mPage + "");
            params.put("size", 6 + "");
            params.put("user_id", mUserid + "");
            request.get(UrlCenter.GET_OPUS, params, mRequestListener);
        }

    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        mPage = 0;
        getData().clear();
        onStartLoading();
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        setPullToRefreshEnable(scrollY == 0);

        if (scrollY < (getResources().getDimensionPixelOffset(R.dimen.headerHeight))) {
            ViewHelper.setTranslationY(mHeaderView, scrollY / 2);
        }
        //淡入淡出动画
        if (scrollY < (getResources().getDimensionPixelOffset(R.dimen.headerHeight) - 100)) {
            if (!isHide) {
                YoYo.with(Techniques.FadeIn)
                        .duration(200)
                        .playOn(relytViewHeader);
                isHide = !isHide;
            }
        } else {
            if (isHide) {
                YoYo.with(Techniques.FadeOutLeft)
                        .duration(200)
                        .playOn(relytViewHeader);
                isHide = !isHide;
            }
        }
    }

    @Override
    public void onDownMotionEvent() {

    }

    boolean isExit = true;

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        try {
            switch (scrollState) {
                case UP:
                    if (isExit) {
                        YoYo.with(Techniques.FadeOutDown)
                                .duration(200)
                                .playOn(mBtnFloating);
                    }
                    isExit = false;
                    break;
                case DOWN:
                    if (!isExit) {
                        YoYo.with(Techniques.FadeInDown)
                                .duration(200)
                                .playOn(mBtnFloating);

                    }
                    isExit = true;
                    break;
            }
        } catch (NullPointerException e) {

        }
    }


    /**
     * 获取用户数据
     */
    private void getUserInfo() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.USER, mUserid + "");
        request.get(url, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Account o) {
                initViewUserInfo(o);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 关注
     */
    private void addAttention() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.POST_USER_FOLLOW, mUserid);
        request.post(url, new UrlParams(), new DataRequestListener(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Object o) {
                setFollowState(2);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 取消关注
     */
    private void deleteAttention() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.POST_USER_FOLLOW, mUserid);
        request.delete(url, new UrlParams(), new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                setFollowState(0);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void initViewUserInfo(final Account o) {
        tvClubName.setText(o.getNickName());
        tvClubID.setText(getString(R.string.idNum, o.getUserId() + ""));
        tvClubPlace.setText(o.getCity());
        tvFansNum.setText(getString(R.string.fansNum, o.getFans() + ""));
        IML.load(this, civHead, o.getPortrait());
        tvUserSign.setText(o.getSign());
        if (o.getFriend().equals("false")) {
            mBtnFloating.setText("加好友");
            mBtnFloating.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addFriend(o);
                }
            });
        } else {
            mBtnFloating.setText("发消息");

            mBtnFloating.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ChatHelper.startSingleChat(UserCenterActivity.this, o.getPhone(), o.getNickName(), o.getPortrait());
                }
            });
        }

        setFollowState(o.getFollowState());
        Glide.with(this)
                .load(o.getPortrait())
                .crossFade(1000)
                .bitmapTransform(new BlurTransformation(this, 23, 4),// “23”：设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”。
                        new ColorFilterTransformation(this, Color.argb(60, 96, 96, 96)))
                .into(mViewHeader);
    }
    private void addFriend(final Account o) {
                      /*  final EditDialogFragment reasonDialog = new EditDialogFragment();
                        reasonDialog.setOnCententSavedListener(new EditDialogFragment.OnContentSavedListener() {
                            @Override
                            public void OnContentSaved(final CharSequence content) {
                                requestAddFriend("" + people.getUser_id(), content.toString());
                                reasonDialog.dismiss();
                            }
                        })
                                .setTitle("请输入申请理由")
                                .show(activity.getSupportFragmentManager());
*/

            final CommentDialog commentDialog = CommentDialog.newInstance("申请理由", "请输入申请理由", 4, true);
            commentDialog.show(getSupportFragmentManager(),"dd");
            commentDialog.setOnClickable(new CommentDialog.CommentClickable() {

                @Override
                public void btnEnter(final String comment) {
                    requestAddFriend("" + o.getUserId(), comment);
                    commentDialog.dismiss();
                }
            });

        }

    //添加为好友
    void requestAddFriend(String userId, String content) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("target_id", userId);
            jsonObject.put("reason", content);
            Log.e("userIduserId","userId = "+userId);
            Log.e("reasonreason","content = "+content);
            IHttpRequest request = new MyHttpRequest(UserCenterActivity.this);
            request.post(UrlCenter.REQEST_ADD_FRIEND, jsonObject, new DataRequestListener<Object>(Object.class) {

                @Override
                public void onSuccess(Object acct) {
                    super.onSuccess(acct);
                    EasyToast.showToast(UserCenterActivity.this, "申请成功，请等待");
//                    notifyDataSetChanged();
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(UserCenterActivity.this, strMsg);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 0:未关注,1:粉丝,2:已关注,3:相互关注
     *
     * @param followState
     */
    public void setFollowState(int followState) {
        mFollowState = followState;
        switch (followState) {
            case 2:
            case 3:
                btnAttention.setText("已关注");
                break;
            case 0:
            case 1:
                btnAttention.setText("关注");
                break;

        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("UserCenter Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient.connect();
        AppIndex.AppIndexApi.start(mClient, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(mClient, getIndexApiAction());
        mClient.disconnect();
    }
}
